<template>
  <div class="shiti-box">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{$route.query.id?'试题修改':'试题录入'}}</span>
      </div>
      <el-form label-width="120px" :rules="rules" ref="form" :model="formData">
        <el-form-item label="学科：" prop="subjectID">
          <el-select
            v-model="formData.subjectID"
            placeholder="请选择"
            style="width: 400px"
            @change="changeSubject"
          >
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录：" prop="catalogID">
          <el-select
            v-model="formData.catalogID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in catalogue"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业：" prop="enterpriseID">
          <el-select
            v-model="formData.enterpriseID"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="item in enterprise"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-row class="loaction">
          <el-form-item label="城市：" prop="province">
            <el-select
              v-model="formData.province"
              placeholder="请选择"
              style="width: 198px"
              @change="changeProvince"
            >
              <el-option
                v-for="(item, index) in provinces"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label-width="0" prop="city">
            <el-select
              v-model="formData.city"
              placeholder="请选择"
              style="width: 198px; margin-left: 4px"
            >
              <el-option
                v-for="(item, index) in citys"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item label="方向：" prop="direction">
          <el-select
            v-model="formData.direction"
            placeholder="请选择"
            style="width: 400px"
          >
            <el-option
              v-for="(item, index) in direction"
              :key="index"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group v-model="formData.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value"
              @change.native="questionTypeChange(item.value)"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
          <el-radio-group v-model="formData.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干：" prop="question">
          <quill-editor
            v-model="formData.question"
            @blur="$refs.form.validateField('question')"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="选项：" prop="options" v-if="formData.questionType!==3" ref="options">
          <div class="options">
            <div
              class="option_item"
              v-for="(item,index) in formData.options"
              :key="item.code"
            >
              <!-- 单选 -->
              <el-radio-group v-model="optionsRadio" v-if="formData.questionType !== 2">
                <el-radio :label="item.code" @change="collectRadio(index)">{{ item.code + " ： " }}</el-radio>
              </el-radio-group>
              <!-- 多选 -->
              <el-checkbox-group v-model="checkList" v-else>
                <el-checkbox :label="item.code" @change="collectCheck">{{ item.code + " ： " }}</el-checkbox>
              </el-checkbox-group>
              <!-- 输入框 -->
              <el-input v-model="item.title" style="width: 240px"></el-input>
              <!-- 图片 -->
              <div class="upload-pic">
                <el-upload
                  ref="upload"
                  :class="{hide:item.img!==''}"
                  action="#"
                  :auto-upload="false"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
                  :on-change="handleChange"
                  @change.native="findUrlIndex(index)"
                  @click.native="clickUrlIndex(index)"
                >
                  <span>上传图片</span>
                  <i class="el-icon-circle-close"></i>
                </el-upload>
                <el-dialog :visible.sync="picVisible[index]" title="预览">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="danger"
            size="small"
            :disabled="formData.questionType !== 2"
            @click="addQuestion"
            >+增加选项与答案
          </el-button>
        </el-form-item>
        <el-form-item label="解析视频：" prop="videoURL">
          <el-input v-model="formData.videoURL"></el-input>
        </el-form-item>
        <el-form-item label="答案解析：" prop="answer">
          <quill-editor
            v-model="formData.answer"
            @blur="$refs.form.validateField('answer')"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="题目备注：" prop="remarks">
          <el-input
            type="textarea"
            v-model="formData.remarks"
            style="width: 400px"
            :rows="4"
          ></el-input>
        </el-form-item>
        <el-form-item label="试题标签：" prop="tags">
          <el-select
            v-model="formData.tags"
            multiple
            allow-create
            filterable
            default-first-option
            placeholder="请选择试题与标签"
            style="width: 400px"
          >
            <el-option
              v-for="(item,index) in tags"
              :key="index"
              :label="item.label"
              :value="item.label"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="$route.query.id" type="success" @click="editSave">确认修改</el-button>
          <el-button v-else type="primary" @click="add">确认提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { subjectsSimple } from '@/api/hmmm/subjects'
import { list } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, difficulty, questionType } from '@/api/hmmm/constants'
import { directionSimple } from '@/api/hmmm/directorys'
import { tagsSimple } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      // 富文本编辑
      editorOption: {
        placeholder: '输入文本...',
        theme: 'snow',
        modules: {
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
              [{ list: 'ordered' }, { list: 'bullet' }], // 列表
              ['blockquote', 'code-block'], // 引用，代码块
              ['clean'], // 清除字体样式
              ['image', 'video'] // 上传图片、上传视频
            ]
          }
        }
      },
      formData: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: 1,
        difficulty: 1,
        question: '',
        options: [],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'blur' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          { required: true, message: '请输入答案解析', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请输入试题标签', trigger: 'blur' }
        ]
      },
      simple: {
        subjectName: ''
      },
      companys: {
        // page:null,
        pagesize: 10000
      },
      subjects: [],
      catalogue: [],
      enterprise: [],
      provinces: [],
      citys: [],
      tags: [],
      direction,
      difficulty,
      questionType,
      optionsRadio: '',
      dialogImageUrl: '',
      picVisible: [false],
      checkList: [], // 复选框
      urlIndex: null,
      clickIndex: null
    }
  },
  async created () {
    this.getsimple()
    this.list()
    this.provinces = provinces()
    this.optionsInit()
    // 精选题库
    if (this.$route.query.id) {
      // 回显数据
      const res = await detail(this.$route.query)
      console.log(res.data)
      res.data.questionType = res.data.questionType - 0
      res.data.difficulty = res.data.difficulty - 0
      console.log(res.data.tags)
      this.formData = res.data
      this.formData.tags = [this.formData.tags]
      // // 学科获取目录和试题
      this.changeSubject()
    }
  },
  beforeRouteUpdate(to, form, next) {
    this.id = to.query.id
    if (!this.id) {
      this.$refs.form.resetFields()
      this.formData = {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: 1,
        difficulty: 1,
        question: '',
        options: [],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      }
    }
    next()
  },
  methods: {
    // 选项数据初始化
    optionsInit () {
      const list = ['A', 'B', 'C', 'D']
      this.formData.options = list.map((item) => {
        return { code: item, img: '', isRight: false, title: '' }
      })
    },
    // 获取学科
    async getsimple () {
      const { data } = await subjectsSimple()
      this.subjects = data
      // console.log(data)
    },
    // 学科改变获取目录和标签
    async changeSubject () {
      // console.log(this.formData.subjectID)
      const { data } = await directionSimple({
        subjectID: this.formData.subjectID
      })
      console.log(data)
      const res = await tagsSimple({ subjectID: this.formData.subjectID })
      // console.log(res)
      this.catalogue = data
      this.tags = res.data
      // console.log(this.tags)
    },
    // 获取企业
    async list () {
      const { data } = await list(this.companys)
      // console.log(data)
      this.enterprise = data.items
    },
    // 城市改变获取地区
    changeProvince () {
      console.log(this.formData.province)
      this.citys = citys(this.formData.province)
      console.log(this.citys)
    },
    // 题型改变
    questionTypeChange (value) {
      if (value === 1) {
        this.checkList = []
      } else if (value === 2) {
        this.optionsRadio = null
      } else {
        this.checkList = []
        this.optionsRadio = null
      }
      // 清除数据
      this.optionsInit()
      // 清除图片
      this.$refs.upload.forEach((item) => {
        item.uploadFiles = []
      })
      // this.$refs.options.resetField()
    },
    // 收集单选
    collectRadio (index) {
      // 排他思想
      this.formData.options.forEach(item => {
        item.isRight = false
      })
      this.formData.options[index].isRight = true
      console.log(this.formData.options)
    },
    // 收集多选
    collectCheck (value) {
      // console.log(this.checkList)
      this.formData.options.forEach(item => {
        item.isRight = this.checkList.includes(item.code)
      })
      console.log(this.formData.options)
    },
    // 图片下标
    findUrlIndex (index) {
      this.urlIndex = index
    },
    // 点击图片传下标
    clickUrlIndex (index) {
      this.clickIndex = index
    },
    // 上传图片  handleChange 不能传下标
    handleChange (file, fileList) {
      console.log(file)
      // 传下标 和拿下标是同步  所以必须把拿下标放到异步里来
      setTimeout(() => {
        this.formData.options[this.urlIndex].img = file.url
        console.log(this.formData.options[this.urlIndex].img)
        // console.log(this.urlIndex)
      }, 0)
    },
    // 删除图片
    handleRemove (file, fileList) {
      setTimeout(() => {
        this.formData.options[this.clickIndex].img = ''
        file.url = ''
      }, 0)
    },
    // 图片放大
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.picVisible[this.clickIndex] = true
    },
    // 增加选项
    addQuestion () {
      const str = String.fromCharCode(
        this.formData.options[
          this.formData.options.length - 1
        ].code.charCodeAt() + 1
      )
      console.log(str)
      this.formData.options.push({
        code: str,
        img: '',
        isRight: false,
        title: ''
      })
    },
    // 确认提交
    async add () {
      try {
        await this.$refs.form.validate()
        this.formData.questionType = this.formData.questionType + ''
        this.formData.difficulty = this.formData.difficulty + ''
        this.formData.tags = this.formData.tags.toString()
        await add(this.formData)
        this.$message.success('添加成功')
        this.$router.push('/questions/list')
      } catch (error) {
        console.log(error)
      }
    },
    // 基础题库修改
    async editSave() {
      try {
        await this.$refs.form.validate()
        this.formData.questionType = this.formData.questionType + ''
        this.formData.difficulty = this.formData.difficulty + ''
        this.formData.tags = this.formData.tags.toString()
        const res = await update(this.formData)
        console.log(res)
        this.$message.success('修改成功')
        this.$router.push('/questions/list')
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style scoped lang='scss'>
.shiti-box {
  padding: 20px;
}
::v-deep .quill-editor {
  .ql-toolbar.ql-snow {
    padding: 0 8px;
  }
  .ql-editor {
    min-height: 200px;
  }
}
.loaction {
  display: flex;
}
.option_item {
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  .el-radio {
    margin-right: 0;
  }
  .upload-pic {
    display: inline-block;
    position: relative;
    margin-left: 5px;
    vertical-align: middle;
    ::v-deep .el-upload {
      width: 100px;
      height: 60px;
      line-height: 60px;
    }
    ::v-deep .el-upload-list--picture-card .el-upload-list__item {
      width: 100px;
      height: 60px;
      vertical-align: middle;
    }
    .el-icon-circle-close {
      position: absolute;
      top: 1px;
      right: 1px;
      transform: translate(50%, -50%);
      font-size: 18px;
      color: #8c939d;
    }
  }
}
::v-deep .hide .el-upload--picture-card{
  display: none;
}
</style>
